module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage17.Stage17HomeGui".new()
local wEasing = require "wEasing"
system.activate( "multitouch" )

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view

-----------------------------------------------------------------------------

-----------------------------------------------------------------------------
	
end


-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local mainGroup = self.view
	
	-----------------------------------------------------------------------------
local backgroundGroup,stageButtonGroup,homeButtonGroup,generateItemsGroup
local bg,replayButton,leftButton,centerButton,rightButton, transparentImage
local okImage,goodImage,perfectImage

local manageTotalTimer,totalTimer,totalTime
local readyText,goText

local deltaRunTime,deltaTouchTime
local deltaTotalTime

local imageButtons,imageItems1,imageItems2 = {},{},{}
local backgroundButton = {}
local score,scoreText

local existingButton,existingImage = nil,nil

local itemEachTurn
local countDownItems1,countDownItems2 = {},{}
local tFomer,isSaveTime = nil,false
local timeScore = 0

local countTimes = 0
local isCountItem = nil

local frameCount0,frameCount1,frameCount = 0,0,0
local itemVisible = {0,0}
local _itemVisible = {0,0}
local showItem = {}

local PreviousLightItem,nextLightItem = nil,nil
local _gameOver
local isPassTurn
local tStartTran = 0
local tToTran = 0
local isListenRuntime
local _score
local instance
----------------------------------------------
itemEachTurn = 8
----------------------------------------------------------------------------

function init()
	_score = {6,7,8,9,10}
	isListenRuntime = false
	goText.alpha = 0
	isPassTurn = false
	score = 0
	scoreText.alpha = 0
	PreviousLightItem = nil
	nextLightItem = nil
	countTimes = countTimes + 1
	deltaRunTime = 000
	deltaTouchTime = 3000
	totalTime =  2000*itemEachTurn + 500 + deltaTouchTime + deltaRunTime
	deltaTotalTime = deltaRunTime
	okImage.alpha = 0
	goodImage.alpha = 0
	perfectImage.alpha = 0
	
	existingButton = false
	existingImage = false
	totalTimer = timer.performWithDelay(100,manageTotalTimer,0)
	
end

--------------------------- create group -------------------------------
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
---------------------------------------------------------------------
countDownItems1 = {0,0,0,0,0,0}
countDownItems2 = {0,0,0,0,0,0}
----------------------handle function ----------------------
function onButtonTouch(event)
	if(isCountItem == nil)then
		isCountItem = countItem(imageButtons)
	end
	local t = event.target
	local phase = event.phase
	print("touch = ",t.id)
	if(phase == "began")then
		if(tonumber(t.id) == _itemVisible[1])then
		_itemVisible[1] = 0
		if(_itemVisible[2] == 0)then
			----------------- true tapped  -----------------
			timeScore = system.getTimer() - tFomer
			showImageResult(timeScore)
			print("ok")
			isPassTurn = true
			isCountItem = nil
			------------------------ next turn ------------------
		end
	elseif(tonumber(t.id) == _itemVisible[2])then
		_itemVisible[2] = 0
		if(_itemVisible[1] == 0)then
			------------------------ true tap -----------------
			timeScore = system.getTimer() - tFomer
			showImageResult(timeScore)
			print("ok")
			isPassTurn = true
			isCountItem = nil
		end
	else
		gameOver()
	end
	end
end

function showImageResult(deltaTime)
	if(deltaTime >= 0 and deltaTime < 1000)then
		perfectImage.alpha = 1
		goodImage.alpha = 0
		okImage.alpha = 0
	elseif(deltaTime >= 1000 and deltaTime < 2000)then
		perfectImage.alpha = 0
		goodImage.alpha = 1
		okImage.alpha = 0
	elseif(deltaTime >= 2000)then
		perfectImage.alpha = 0
		goodImage.alpha = 0
		okImage.alpha = 1
	end
	score = score + 1
	scoreText.text = score .."PTS"
	scoreText.alpha = 1
end

function manageTotalTimer()
	deltaTotalTime = deltaTotalTime - 100
	if(deltaTotalTime >= 0)then
		readyText.alpha = 1
		readyText.text = math.round(deltaTotalTime/1000)
	elseif(deltaTotalTime <0 and deltaTotalTime >= -1000) then
		perfectImage.alpha = 0
		goodImage.alpha = 0
		okImage.alpha = 0
		readyText.alpha = 0
		goText.alpha = 1
		-- goText.text = "Go"
		if(existingButton ~= true)then
			existingButton = generateButton()
		end
	
	elseif(deltaTotalTime < -1000 and deltaTotalTime >= -2000*itemEachTurn+1000)then
		goText.alpha = 0
		-- Runtime:addEventListener("enterFrame",onEnterFrame)
		-- isListenRuntime = true
		if(existingImage ~= true)then
			existingImage = generateItem(itemEachTurn)
		end
	elseif(deltaTotalTime < -2000*itemEachTurn+1000)then
		Runtime:removeEventListener("enterFrame",onEnterFrame)
		isListenRuntime = false
		for k,v in pairs(imageButtons)do
			display.remove(v)
			v = nil
			k = nil
		end
		for k,v in pairs(imageItems1) do
			display.remove(v)
			v = nil
			k = nil
		end
		for k,v in pairs(imageItems2) do
			display.remove(v)
			v = nil
			k = nil
		end
		
		timer.cancel(totalTimer)
		if(countTimes <= 10)then
			local _tempTime = 1000
			local _tempTimer
			_tempTimer = timer.performWithDelay(100,function()
											_tempTime = _tempTime - 100
											instance.alpha = 1
											if(_tempTime < 0)then
												timer.cancel(_tempTimer)
												itemEachTurn = itemEachTurn + 1
												instance.alpha = 0
												init()
											end
										end,0)
		
			
		else
			finishedGame()
		end
	end
end

function onEnterFrame()
	if(PreviousLightItem == nil)then
		PreviousLightItem = checkLightItem()
		tFomer = system.getTimer()
		countItem(imageButtons)
	end
	if(isCountItem == nil)then
		isCountItem = countItem(imageButtons)
	end
	if(transparentImage.alpha == 1)then
		frameCount1 = frameCount1 + 1
		if(frameCount1 >= 15)then
			frameCount1 = 0
			transparentImage.alpha = 0
		end
	else 
		frameCount0 = frameCount0 + 1
		if(frameCount0 >= 15)then
			frameCount0 = 0
			transparentImage.alpha = 1
		end
	end
	for k,v in pairs(imageItems1)do	
		if((generateItemsGroup.x +v.x) >= transparentImage.x - transparentImage.width/2 
			and (generateItemsGroup.x + v.x) <= transparentImage.x + transparentImage.width/2)then
			
			nextLightItem = checkLightItem()
			if(nextLightItem ~= PreviousLightItem)then
				okImage.alpha = 0
				goodImage.alpha = 0
				perfectImage.alpha = 0
				isCountItem = nil
				PreviousLightItem = nextLightItem
				if(isPassTurn == false)then
					if(checkWin())then
						print("win")
					else gameOver()
					end
				end
				tFomer = system.getTimer()
				-- print(tFomer)
				isPassTurn = false
			end
			if(v.id ~= 7)then
				itemVisible[1] = tonumber(v.id)
			else itemVisible[1] = 0
			end
			v.alpha = 1
		else v.alpha = 0.5
		end
	end
	for k,v in pairs(imageItems2)do
		if((generateItemsGroup.x + v.x) >= transparentImage.x -transparentImage.width/2 
			and (generateItemsGroup.x + v.x) <= transparentImage.x + transparentImage.width/2)then
			if(v.id ~= 7)then
				
				itemVisible[2] = tonumber(v.id)
			else
				itemVisible[2] = 0
			end
			v.alpha = 1
		else v.alpha = 0.5
		end
	end
	-- countItem(imageButtons)
end
----------------------------- helper function ---------------------
local exceptRandom = function(startNumber,endNumber,exceptNumber)
	local temp = {}
	local j = 0
	for i = 1,endNumber-startNumber+1,1 do
		j = j+1
		if(startNumber+i-1 ~= exceptNumber) then 
			temp[j] = startNumber + i -1
		else
			j = j - 1 
		end
	end
	_temp = math.random(1,endNumber - startNumber)
	return temp[_temp]
end

function checkWin()
	-- countItem(imageButtons)
	if(_itemVisible[1] == 0 and _itemVisible[2] == 0)then
		return true
	end
	return false
end

function generateButton()
	local temp1Position = math.random(1,6)
	imageButtons[1] = display.newImageRect(stageButtonGroup,gui.buttonImage[temp1Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[1].x = gui.buttonPosition.x[1]
		imageButtons[1].y = gui.buttonPosition.y[1]
		imageButtons[1].id = temp1Position
	imageButtons[1]:addEventListener("touch",onButtonTouch)
		
	local temp2Position = exceptRandom(1,6,temp1Position)
	imageButtons[2] = display.newImageRect(stageButtonGroup,gui.buttonImage[temp2Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[2].x = gui.buttonPosition.x[2]
		imageButtons[2].y = gui.buttonPosition.y[2]
		imageButtons[2].id = temp2Position
	imageButtons[2]:addEventListener("touch",onButtonTouch)
	
	local temp3Position = 1
	while (temp3Position == temp1Position or temp3Position == temp2Position) do
		temp3Position = math.random(1,6)
	end
	imageButtons[3] = display.newImageRect(stageButtonGroup,gui.buttonImage[temp3Position].fn,gui.buttonPosition.w,gui.buttonPosition.h)
		imageButtons[3].x = gui.buttonPosition.x[3]
		imageButtons[3].y = gui.buttonPosition.y[3]
		imageButtons[3].id = temp3Position
	imageButtons[3]:addEventListener("touch",onButtonTouch)
	
	-- for k,v in pairs(imageButtons)do
		-- print(v.id)
	-- end
	return true
end

function generateItem(itemEachTurn)
	local temp1Position = math.random(1,7)
	imageItems1[1] = display.newImageRect(generateItemsGroup, gui.foodImage[temp1Position].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems1[1].x = 1*gui.displayWidth/4
		imageItems1[1].y = 290
		imageItems1[1].id = temp1Position
	
	local temp2Position = math.random(1,7)
	imageItems1[2] = display.newImageRect(generateItemsGroup, gui.foodImage[temp2Position].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems1[2].x = 2*gui.displayWidth/4 + 20
		imageItems1[2].y = 290
		imageItems1[2].id = temp2Position
	
	local tempPosition
	for i = 3,itemEachTurn,1 do
		tempPosition = math.random(1,7)
		imageItems1[i] = display.newImageRect(generateItemsGroup, gui.foodImage[tempPosition].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems1[i].x = i*gui.displayWidth/4 + 20*(i-1)
		imageItems1[i].y = 290
		imageItems1[i].id = tempPosition
	end
	
	temp1Position = math.random(1,7)
	imageItems2[1] = display.newImageRect(generateItemsGroup, gui.foodImage[temp1Position].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems2[1].x = 1*(gui.displayWidth/4)
		imageItems2[1].y = 190
		imageItems2[1].id = temp1Position
	
	temp2Position = math.random(1,7)
	imageItems2[2] = display.newImageRect(generateItemsGroup, gui.foodImage[temp2Position].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems2[2].x = 2*gui.displayWidth/4 + 20
		imageItems2[2].y = 190
		imageItems2[2].id = temp2Position
		
	for i = 3,itemEachTurn,1 do
		tempPosition = math.random(1,7)
		imageItems2[i] = display.newImageRect(generateItemsGroup, gui.foodImage[tempPosition].fn, gui.buttonPosition.w, gui.buttonPosition.h)
		imageItems2[i].x = i*gui.displayWidth/4 + 20*(i-1)
		imageItems2[i].y = 190
		imageItems2[i].id = tempPosition
	end
	for k,v in pairs(imageItems1)do
		v.alpha = 0.5
	end
	for k,v in pairs(imageItems2)do
		v.alpha = 0.5
	end
	
	-- local i
	-- for i=1,6,1 do
		-- countDownItems[i] = 0
	-- end
	-- for k,v in pairs(imageButtons) do
		-- for k1,v1 in pairs(imageItems) do
			-- if (v.id == v1.id) then
				-- countDownItems[tonumber(v.id)] = countDownItems[tonumber(v.id)] + 1
			-- end
		-- end
	-- end
	----------------------- for test ---------------------
	-- for k,v in pairs(_scoreText) do
		-- display.remove(v)
	-- end
	-- for k,v in pairs(imageButtons)do
		-- _scoreText[k] = display.newText(countDownItems[tonumber(v.id)],v.x+50, v.y - 50,native.systemFontBold,18)
		-- _scoreText[k]:setTextColor(255,0,0)
	-- end
	---------------------------------------------------------
	tStartTran = system.getTimer()
	tToTran = itemEachTurn*2000
	xStartItem =  generateItemsGroup.width/2
	generateItemsGroup.x =  -1 * (itemEachTurn /4)*gui.displayWidth - 20*(itemEachTurn)
	_tran = transition.to(generateItemsGroup,{time = itemEachTurn * 2000, alpha = 1, 
	x = gui.displayWidth-20, y = generateItemsGroup.y, 
	onStart = onStartGenerateItems, onComplete = onFinishGenerateItems })
	return true
end

function onStartGenerateItems()
	Runtime:addEventListener("enterFrame",onEnterFrame)
	isListenRuntime = true
end

function onFinishGenerateItems()
end

function checkLightItem()
	for k,v in pairs(imageItems1)do
		if(v.alpha == 1)then
			return k
		end
	end
	return nil
end

function countItem(imageButtons)
	local flag1,flag2 = false,false
	for k,v in pairs(imageButtons)do
		if(tonumber(v.id) == itemVisible[1])then
			flag1 = true
		end
	end
	for k,v in pairs(imageButtons)do
		if(tonumber(v.id) == itemVisible[2])then
			flag2 = true
		end
	end
	
	if(flag1 == false) then
		_itemVisible[1] = 0
	else _itemVisible[1] = itemVisible[1]
	end
	if(flag2 == false)then
		_itemVisible[2] = 0
	else _itemVisible[2] = itemVisible[2]
	end
	return _itemVisible
end

function gameOver()
	if(_tran ~= nil) then
		transition.cancel(_tran)
	end
	if(totalTimer ~= nil)then
		timer.cancel(totalTimer)
	end
	-- _gameOver = display.newText(mainGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	-- _gameOver.x = display.contentCenterX
	-- _gameOver.y = display.contentCenterY
	-- _gameOver:setTextColor(unpack(gui.score.color))
	-- _gameOver.alpha = 1
	Runtime:removeEventListener("enterFrame",onEnterFrame)
	
	local temp = math.max(0,countTimes - 6)
	g1 = require "popup.popupWin".new(score,temp,_score,onReplayButtonTap)
	transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
end

function onResumeFromPopup()
	if(isListenRuntime == true)then
		Runtime:addEventListener("enterFrame",onEnterFrame)
	end
	timer.resume(totalTimer)
	_tran = transition.to(generateItemsGroup,{time = tToTran, alpha = 1, 
			x = gui.displayWidth - 20, y = generateItemsGroup.y})
end

function onStartPopup()
	if(isListenRuntime == true)then
		Runtime:removeEventListener("enterFrame",onEnterFrame)
	end
	timer.pause(totalTimer)
	if(_tran ~= nil)then
		transition.cancel(_tran)
	end	
	tToTran = tToTran - (system.getTimer() - tStartTran)
end

function finishedGame()
	print("victory")
end

function onReplayButtonTap()
	-- scoreText.text = "0 PTS"
	Runtime:removeEventListener("enterFrame",onEnterFrame)
	itemEachTurn = 8
	countTimes = 0
	-- if(_gameOver ~= nil)then
		-- _gameOver.alpha = 0
	-- end
	if(totalTimer)then
		timer.cancel(totalTimer)
	end
	existingButton = false
	existingImage = false
	for k,v in pairs(imageButtons)do
		if(v.id ~= nil)then
			-- v:removeEventListener("tap",onTapButton)
			-- table.remove(imageButtons,k)
			display.remove(v)
			v = nil
			k = nil
		end
	end
	imageButtons = {}
	for k,v in pairs(imageItems1)do
		display.remove(v)
		v = nil
		k = nil
	end
	imageItems1 = {}
	for k,v in pairs(imageItems2)do
		display.remove(v)
		v = nil
		k = nil
	end
	imageItems2 = {}
	if(_tran)then
		transition.cancel(_tran)
	end
	init()
end

do -------------------- background and button --------------------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y
	
pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		mainGroup:insert(group2)
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup })
	end
})

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})

end 
do ------------------------------- image result -------------------
transparentImage = display.newImageRect(homeButtonGroup,gui.transparentImage.fn,gui.transparentImage.w,gui.transparentImage.h)
	transparentImage.x = gui.transparentImage.x
	transparentImage.y = gui.transparentImage.y

local sheet1 = graphics.newImageSheet( gui.action.fn, { width=gui.action.w, height=gui.action.h, numFrames=1 } )
	instance = display.newSprite( sheet1, { name = "action", start=1, count=1, time=1000 } )
	instance.x = gui.action.x
	instance.y = gui.action.y
	instance.xScale = 0.5
	instance.yScale = 0.5
	instance:play()
	instance.alpha = 0
stageButtonGroup:insert(instance)	

okImage = display.newImageRect(homeButtonGroup,gui.okImage.fn,gui.okImage.w,gui.okImage.h)
	okImage.x = gui.okImage.x
	okImage.y = gui.okImage.y
	okImage.alpha = 0

goodImage = display.newImageRect(homeButtonGroup,gui.goodImage.fn,gui.goodImage.w,gui.goodImage.h)
	goodImage.x = gui.goodImage.x
	goodImage.y = gui.goodImage.y
	goodImage.alpha = 0

perfectImage = display.newImageRect(homeButtonGroup,gui.perfectImage.fn,gui.perfectImage.w,gui.perfectImage.h)
	perfectImage.x = gui.perfectImage.x
	perfectImage.y = gui.perfectImage.y
	perfectImage.alpha = 0
end

	
mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(homeButtonGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(replayButton)
mainGroup:insert(pauseButton)
do ------------------------------- score -------------------
scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	scoreText.alpha = 0
homeButtonGroup:insert(scoreText)

------------------------------------ text ----------------------------------------------------
readyText = display.newText(mainGroup, "2",160 , 150, gui.timer.font, gui.timer.fontSize+20)
	readyText:setTextColor(255,0,0)
	readyText.alpha = 0
-- goText = display.newText(mainGroup, "GO", 160 -30, 150, gui.timer.font, gui.timer.fontSize+20)
	-- goText:setTextColor(255,0,0)
	-- goText.alpha = 0
goText = display.newImageRect(mainGroup,gui.goImage.fn,gui.goImage.w,gui.goImage.h)
	goText.x = gui.goImage.x
	goText.y = gui.goImage.y
	goText.alpha = 0
end
------------------------------------- run test ----------------------------

init()
----------------------------------- end run --------------------------------
	-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene